package com.app.onebuy.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.app.onebuy.R;
import com.app.onebuy.basis.BasisActivity;
import com.app.onebuy.basis.Constants;
import com.app.onebuy.bean.BasisBean;
import com.app.onebuy.bean.LoginBean;
import com.app.onebuy.home.HomeTabActivity;
import com.app.onebuy.login.countrychoose.CountryChooseActivity;
import com.app.onebuy.login.countrychoose.CountryListDate;
import com.app.onebuy.util.TextLengthUtil;
import com.bumptech.glide.gifdecoder.GifHeaderParser;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.flyco.dialog.listener.OnBtnClickL;

import java.util.Arrays;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jiguang.share.android.api.AuthListener;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.model.AccessTokenInfo;
import cn.jiguang.share.android.model.BaseResponseInfo;
import cn.jiguang.share.android.model.UserInfo;
import cn.jiguang.share.android.utils.Logger;
import cn.jiguang.share.facebook.Facebook;
import my.DialogUtils;
import my.LogUtil;
import my.MD5;
import my.MySharedPreferences;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

import static android.R.attr.action;

public class LoginActivity extends BasisActivity {


    @BindView(R.id.eidt_user)
    EditText edit_user;
    @BindView(R.id.edit_pwd)
    EditText edit_pwd;

    @BindView(R.id.text_mobile_zone_num)
    TextView text_mobile_zone_num;
    @BindView(R.id.login_button)
    LoginButton login_button;

    CountryListDate countryListDate;

    CallbackManager  callbackManager;

    public static void ToLogin(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, LoginActivity.class);
        activity.startActivityForResult(intent, requestCode);

    }

    public static boolean toLoginIfNotLogin(Activity context, int requestCode) {
        if (!LoginBean.isLogin()) {
            ToLogin(context, requestCode);
            return false;
        }
        return true;

    }

    public static boolean toLoginIfNotLoginDialog(final Activity context, final int requestCode) {
        if (!LoginBean.isLogin()) {
            DialogUtils.DialogTwo(context, "", context.getResources().getString(R.string.app_not_login_hint), context.getResources().getString(R.string.app_login_now), context.getResources().getString(R.string.app_cancel), new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    ToLogin(context, requestCode);
                }
            }, null);

            return false;
        }
        return true;

    }

    public static void ToLogin(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);

    }


    public static void toLoadingAllClear(Context mContext) {
        LoginBean.logout();
        Intent intent = new Intent(mContext, HomeTabActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
//				| Intent.FLAG_ACTIVITY_NEW_TASK);
//		intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
//        mContext.finish();
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.login_activity);
        setTitle("");
        setTitleBg(R.color.base_color_red);
        setTitleRightButton(R.drawable.icon_close_white, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
//        setTitleLeftButton(null);
        edit_user.setFilters(new InputFilter[]{filter});

    }

    //禁止输入换行  和   空格
    private InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source.equals(" ") || source.toString().contentEquals("\n")) return "";
            else return null;
        }
    };

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);

//        edit_user.setText("13695049660");
//        edit_user.setText("15880214362");
//        edit_pwd.setText("123456");


        CountryListDate dateCountry = CountryListDate.getFromCache();
        if (dateCountry == null) {
            //{"codeOk":false,"mobile_prefix":"63","pinyin_all":"FEILVBIN","pinyin_first":"f","pinyin_simple":"FLB","statusCode":-1,"title":"菲律宾"}
            //{"codeOk":false,"mobile_prefix":"86","pinyin_all":"ZHONGGUO","pinyin_first":"z","pinyin_simple":"ZG","statusCode":-1,"title":"中国"}
            countryListDate = new CountryListDate();
            countryListDate.setId("63");
            countryListDate.setEn_name("FEILVBIN");
            countryListDate.setCn_name("菲律宾");
            countryListDate.setTel_code("63");
            countryListDate.save();
        } else {
            countryListDate = dateCountry;
        }
        countryListDate.save();

        setCountryView();
        LoginManager.getInstance().logOut();
        callbackManager = CallbackManager.Factory.create();
        login_button.setReadPermissions(Arrays.asList("email"));
        // If you are using in a fragment, call loginButton.setFragment(this);

        // Callback registration
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
             String userid =   loginResult.getAccessToken().getUserId();
                loginBySso("facebook", userid);
                // App code
            }

            @Override
            public void onCancel() {
                // App code
                showToast("Auth cancel");
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
                showToast("Auth failed");
            }
        });
    }


    public static final int REQUEST_REGISTER = 11;
    private final int REQUEST_FOGET = 13;
    private final int REQUEST_COUNTRY = 15;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_FOGET:
                if (resultCode == Activity.RESULT_OK) {
                }
                break;
            case REQUEST_REGISTER:
                if (resultCode == Activity.RESULT_OK) {
                    setResult(Activity.RESULT_OK);
                    finish();
                }
                break;
            case REQUEST_COUNTRY:
                if (resultCode == Activity.RESULT_OK) {
                    countryListDate = (CountryListDate) data.getSerializableExtra("data");
                    countryListDate.save();
                    LogUtil.i(JSON.toJSONString(countryListDate));
                    setCountryView();
                }
                break;
            default:
                callbackManager.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    @OnClick(R.id.img_close)
    void close() {
        finish();
    }

    @OnClick(R.id.btn_login)
    void login() {
        doLogin();
    }


    @OnClick(R.id.text_regist)
    void regist() {
        Intent intent = new Intent(this, RegistActivity.class);
        startActivityForResult(intent, REQUEST_REGISTER);
    }

    @OnClick(R.id.text_forgetpwd)
    void fogetpwd() {
        Intent intent = new Intent(this, ForgetPwdActivity.class);
        startActivityForResult(intent, REQUEST_FOGET);
    }


    String userName, password;

    void doLogin() {

        userName = edit_user.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            showToast(R.string.user_user_empty);
            return;
        }


        password = edit_pwd.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            showToast(R.string.user_password_empty);
            return;
        }

        if (!TextLengthUtil.mixLength(password)) {
            showToast(R.string.edit_mix_length);
            return;
        }

        MyParams params = new MyParams();
        params.put("mobile", userName);
        params.put("password", MD5.getMD5ofStrLowercase(password));
        params.put("mobile_prefix", countryListDate.getTel_code());
        showLoading();
        MyHttpUtils.post(Constants.URL_USER_LOGIN, params, myHttpListener, HTTP_LOGIN, LoginBean.class);
//
    }

    static final int HTTP_LOGIN = 12;
    static final int HTTP_SMS = 13;
    MyHttpListener myHttpListener = new MyHttpListener() {
        @Override
        public void onSuccess(int httpWhat, Object result) {
            switch (httpWhat) {
                case HTTP_LOGIN:
                    LoginBean loginBean = (LoginBean) result;
                    onLoginSuccess(loginBean);
                    break;
//                case HTTP_SMS:
////                    showToast("短信验证码获取成功");
//                    showToast(((BasisBean) result).getResultData());
//                    new CountDownTimerUtils(btn_msgcode).start();
//                    break;
            }
        }

        @Override
        public void onFailure(int httpWhat, Object result) {

            if (result != null && ((BasisBean) result).getStatusCode() == 410) {

//                showToast(R.string.regist_alreadyread);
                Intent intent = new Intent(mContext, RegistActivity.class);
                intent.putExtra("openid", open_id);
                intent.putExtra("name", nickname);
                mContext.startActivityForResult(intent, REQUEST_REGISTER);
//                getThirpartInfo();
            } else {
                super.onFailure(httpWhat, result);
            }
        }

        @Override
        public void onFinish(int httpWhat) {
            dismissProgress();
        }
    };

    protected void onLoginSuccess(LoginBean loginBean) {
//        showToast("登录成功");
        showToast(R.string.login_successfully);
        setResult(Activity.RESULT_OK);
        loginBean.save();


        MySharedPreferences mSp = new MySharedPreferences(this);
        mSp.putUser(userName);
        if (!TextUtils.isEmpty(password)) {
            mSp.putPassword(password);
        }
        finish();
    }

    private void onResultOk() {
        setResult(Activity.RESULT_OK);
        finish();
    }

    @OnClick(R.id.view_country)
    void countryClick() {
        Intent intent = new Intent(mContext, CountryChooseActivity.class);
        startActivityForResult(intent, REQUEST_COUNTRY);
    }

    void setCountryView() {

        text_mobile_zone_num.setText(countryListDate.getTel_code());
    }

    AccessTokenInfo AuthInfo;
//    public void facebookLoogin(View view){
////        loginBySso("facebook","test_123456");
//        JiGuangUtil.getUserInfo(Facebook.Name, new JiGuangUtil.JiGuangSsoInfoGet() {
//            @Override
//            public void onSsoGet(AccessTokenInfo userInfo) {
//                loginBySso("facebook",userInfo.getOpenid());
//            }
//
//            @Override
//            public void onFailed(String msg) {
////                showToast(msg);
//                showToast(R.string.login_third_failed);
//            }
//        });
//    }

    String open_id;
    String nickname;

    public void facebookLoogin(View view) {
        JShareInterface.authorize(Facebook.Name, new AuthListener() {
            @Override
            public void onComplete(Platform platform, int i, BaseResponseInfo data) {
                Logger.dd(GifHeaderParser.TAG, "onComplete:" + platform + ",action:" + action + ",data:" + data);
                String toastMsg = null;
                if (data instanceof AccessTokenInfo) {        //授权信息
                    String token = ((AccessTokenInfo) data).getToken();// token
                    long expiration = ((AccessTokenInfo) data).getExpiresIn();// token有效时间，时间戳
                    String refresh_token = ((AccessTokenInfo) data).getRefeshToken();//refresh_token
                    String openid = ((AccessTokenInfo) data).getOpenid();//openid
                    //授权原始数据，开发者可自行处理
                    String originData = data.getOriginData();
                    toastMsg = "授权成功:" + data.toString();
                    Logger.dd(GifHeaderParser.TAG, "openid:" + openid + ",token:" + token + ",expiration:" + expiration + ",refresh_token:" + refresh_token);
                    Logger.dd(GifHeaderParser.TAG, "originData:" + originData);
                    open_id = openid;
                    nickname = openid;
                    loginBySso("facebook", openid);
                }
            }

            @Override
            public void onError(Platform platform, int i, int i1, Throwable throwable) {
//                String toastMsg = null;
//                switch (action) {
//                    case Platform.ACTION_AUTHORIZING:
//                        toastMsg = "授权失败";
//                        break;
//                }
                showToast(R.string.login_third_failed);
            }

            @Override
            public void onCancel(Platform platform, int i) {
//                Logger.dd(GifHeaderParser.TAG, "onCancel:" + platform + ",action:" + action);
//                String toastMsg = null;
//                switch (action) {
//                    case Platform.ACTION_AUTHORIZING:
//                        toastMsg = "取消授权";
//                        break;
//                }
                showToast(R.string.login_third_failed);
            }
        });
    }

    public void loginBySso(String sso_type, String open_id) {

        MyParams params = new MyParams();
        params.put("sso_type", sso_type);
        params.put("open_id", open_id);
        showLoading();
        MyHttpUtils.post(Constants.URL_USER_SSO_LOGIN, params, myHttpListener, HTTP_LOGIN, LoginBean.class);
    }

    public void getThirpartInfo() {
        JShareInterface.getUserInfo(Facebook.Name, new AuthListener() {
            @Override
            public void onComplete(Platform platform, int i, BaseResponseInfo data) {
                Logger.dd(GifHeaderParser.TAG, "onComplete:" + platform + ",action:" + action + ",data:" + data);
                String toastMsg = null;
//                switch (action) {
//                    case Platform.ACTION_USER_INFO:
                        if (data instanceof UserInfo) {      //第三方个人信息
                            String openid = ((UserInfo) data).getOpenid();  //openid
                            String name = ((UserInfo) data).getName();  //昵称
                            String imageUrl = ((UserInfo) data).getImageUrl();  //头像url
                            int gender = ((UserInfo) data).getGender();//性别, 1表示男性；2表示女性
                            //个人信息原始数据，开发者可自行处理
                            String originData = data.getOriginData();
                            toastMsg = "获取个人信息成功:" + data.toString();
                            LogUtil.i("openid:" + openid + ",name:" + name + ",gender:" + gender + ",imageUrl:" + imageUrl);
                            LogUtil.i("originData:" + originData);

                            Intent intent = new Intent(mContext, RegistActivity.class);
                            intent.putExtra("openid", openid);
                            intent.putExtra("name", name);
                            mContext.startActivityForResult(intent, REQUEST_REGISTER);
//                        }
//                        break;
                }
            }

            @Override
            public void onError(Platform platform, int i, int i1, Throwable error) {
                Logger.dd(GifHeaderParser.TAG, "onError:" + platform + ",action:" + action + ",error:" + error);
                String toastMsg = null;
//                switch (action) {
//                    case Platform.ACTION_USER_INFO:
//                        toastMsg = "获取个人信息失败";
//                        Toast.makeText(mContext, ""+toastMsg, Toast.LENGTH_SHORT).show();
//                        break;
//                    default:
//                        Toast.makeText(mContext, "获取失败", Toast.LENGTH_SHORT).show();
//                        break;
//                }

                showToast(R.string.login_third_failed);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Logger.dd(GifHeaderParser.TAG, "onCancel:" + platform + ",action:" + action);
                String toastMsg = null;
//                switch (action) {
//                    case Platform.ACTION_USER_INFO:
//                        toastMsg = "取消获取个人信息";
//                        Toast.makeText(mContext, ""+toastMsg, Toast.LENGTH_SHORT).show();
//                        break;
//                }

                showToast(R.string.login_third_failed);
            }
        });
    }


    @OnClick(R.id.btn_loginfacebook)
     void loginFacebookOfficial(){
        LoginManager.getInstance().logInWithReadPermissions(mContext,Arrays.asList("email"));
    }
}
